import sqlite3
import os
from database_analyzer import DatabaseAnalyzer
from models import DatabaseConnection, DatabaseType

def test_sqlite_connection():
    """测试SQLite连接"""
    print("=== 测试SQLite连接 ===")
    
    # 检查示例数据库文件是否存在
    db_file = "example_ecommerce.db"
    if not os.path.exists(db_file):
        print(f"错误: 数据库文件 {db_file} 不存在")
        return False
    
    try:
        # 测试基本连接
        conn = sqlite3.connect(db_file)
        cursor = conn.cursor()
        
        # 获取所有表
        cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
        tables = cursor.fetchall()
        print(f"SQLite直接查询到的表: {[table[0] for table in tables]}")
        
        conn.close()
        
        # 使用我们的分析器测试
        connection_info = DatabaseConnection(
            db_type=DatabaseType.SQLITE,
            database=db_file
        )
        
        analyzer = DatabaseAnalyzer(connection_info)
        tables = analyzer.get_tables()
        
        print(f"分析器返回的表数量: {len(tables)}")
        for table in tables:
            print(f"  - {table.name}: {len(table.columns)} 列")
        
        relationships = analyzer.get_relationships()
        print(f"分析器返回的关系数量: {len(relationships)}")
        for rel in relationships:
            print(f"  - {rel.from_table}.{rel.from_column} -> {rel.to_table}.{rel.to_column}")
        
        analyzer.close()
        return len(tables) > 0
        
    except Exception as e:
        print(f"SQLite测试失败: {str(e)}")
        import traceback
        traceback.print_exc()
        return False

def test_connection_step_by_step():
    """逐步测试连接过程"""
    print("\n=== 逐步测试连接过程 ===")
    
    db_file = "example_ecommerce.db"
    if not os.path.exists(db_file):
        print(f"错误: 数据库文件 {db_file} 不存在")
        return
    
    try:
        from sqlalchemy import create_engine, inspect
        
        # 创建引擎
        connection_string = f"sqlite:///{db_file}"
        print(f"连接字符串: {connection_string}")
        
        engine = create_engine(connection_string)
        print("引擎创建成功")
        
        # 创建检查器
        inspector = inspect(engine)
        print("检查器创建成功")
        
        # 获取表名
        table_names = inspector.get_table_names()
        print(f"SQLAlchemy查询到的表名: {table_names}")
        
        if table_names:
            # 测试第一个表的详细信息
            first_table = table_names[0]
            print(f"\n测试表 '{first_table}' 的详细信息:")
            
            columns = inspector.get_columns(first_table)
            print(f"  列信息: {len(columns)} 列")
            for col in columns[:3]:  # 只显示前3列
                print(f"    - {col['name']}: {col['type']}")
            
            pk_constraint = inspector.get_pk_constraint(first_table)
            print(f"  主键约束: {pk_constraint}")
            
            foreign_keys = inspector.get_foreign_keys(first_table)
            print(f"  外键: {len(foreign_keys)} 个")
            for fk in foreign_keys:
                print(f"    - {fk}")
        
        engine.dispose()
        print("\n逐步测试完成")
        
    except Exception as e:
        print(f"逐步测试失败: {str(e)}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    print("开始调试数据库分析器...")
    
    # 测试SQLite示例数据库
    success = test_sqlite_connection()
    
    # 逐步测试
    test_connection_step_by_step()
    
    if success:
        print("\n✅ SQLite测试通过！")
    else:
        print("\n❌ SQLite测试失败！")